<?php

namespace App\Console\Commands\College;

use App\Models\College\CollegeTrainingOrderModel;
use App\Models\College\CollegeTrainingPlanModel;
use Illuminate\Console\Command;

class UpdateTrainingPlansStatus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'college:update-training-plans-status';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新培训计划状态';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        //查询培训计划结束的记录
        $collegeTrainingPlansIds = CollegeTrainingPlanModel::query()
            ->where('status', CollegeTrainingPlanModel::TRAINING_PLANS_STATUS_DEFAULT)
            ->where('planEndTime', '<', time())
            ->pluck('id')
            ->toArray();
        if ($collegeTrainingPlansIds) {
            //查询当前培训计划是否存在培训订单
            $collegeTrainingPlansOrderIds = CollegeTrainingOrderModel::query()
                ->whereIn('planId', $collegeTrainingPlansIds)
                ->pluck('id', 'planId')->toArray();
            foreach ($collegeTrainingPlansIds as $v) {
                //培训周期结束时
                //无培训订单 状态修改为 关闭
                $status = CollegeTrainingPlanModel::TRAINING_PLANS_STATUS_OFF;
                if (isset($collegeTrainingPlansOrderIds[$v]) && $collegeTrainingPlansOrderIds[$v]) {
                    //有培训订单 状态修改为 完成
                    $status = CollegeTrainingPlanModel::TRAINING_PLANS_STATUS_SUC;
                }
                CollegeTrainingPlanModel::query()->where(['id' => $v, 'status' => CollegeTrainingPlanModel::TRAINING_PLANS_STATUS_DEFAULT])->update([
                    'status' => $status,
                ]);
            }
        }
    }
}
